const Http = require('./http.lib');
const Promise = require('./promise.lib');
const environment = require('../config/environment.config');
const _ = require('lodash');
const queryString = require('querystring');


/**
 * Promise工厂对象
 */
class PromiseFactory extends Promise {
    constructor() {
        super();
        this.http = new Http();
    }
    producePromise(...args) {
        return this.createPromise.apply(this, args);
    }
}

/**
 * http请求封装
 */
class HttpClient extends PromiseFactory {
    constructor() {
        super();
    }
    get(params) {
        if (_.isString(params)) {
            params = {
                path: params
            }
        }
        let path = environment.HTTP.GET + params.path,
            p = queryString.stringify(params.params);
        if (!_.isEmpty(p)) {
            p = '?' + p;
        }
        return this.producePromise(global.simpleBind(this.http.get, this.http), path, p);
    }
    post(ctx, params) {
        return this.request(ctx, params);
    }
    request(ctx, params) {
        let cookie = global.getCookie(ctx);
        let options = {
            hostname: environment.HTTP.PORT,
            port: environment.HTTP.PORT,
            method,
            path: params.path,
            headres: { Cookie: cookie },
            params: params.params
        }
        return this.producePromise(global.simpleBind(this.http.request, this.http), options);
    }
}

module.exports = global.buildClass(HttpClient);
